package com.chushouya.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;

/**
 * 加签/验签工具类
 *
 * @author qingyoupin
 */
@Slf4j
public class SuhuishouSignUtil {
    /**
     * 生成签名
     * @param paramMap 参数Map
     * @param timestamp  系统时间戳, timestamp不参与请求参数ASCII排序
     * @param appKey 合作商的appKey, appKey不参与请求参数ASCII排序
     * @return sign
     */
    public static String genMd5Sign(Map<String, Object> paramMap, final String timestamp, final String appKey) {
        log.info("====> genMd5Sign, paramMap: {}, timestamp: {}, appKey: {}", paramMap, timestamp, appKey);
        // 排序
        Set<String> set = paramMap.keySet();
        TreeMap<String,String> treeMap = new TreeMap<>();
        for(String key: set){
            if(Objects.nonNull(paramMap.get(key))) {
                treeMap.put(key, paramMap.get(key).toString());
            }
        }
        // 拼接
        Set<Map.Entry<String, String>> setKey = treeMap.entrySet();
        StringBuilder sb = new StringBuilder();
        setKey.forEach(e -> {
            sb.append(e.getKey()).append(e.getValue());
        });
        // 追加timestamp、appKey到参数尾部
        sb.append("timestamp").append(timestamp);
        sb.append("appKey").append(appKey);
        final String data = sb.toString();
        log.info("====> DigestUtils.md5Hex: {}", data);
        // MD5加密得到签名
        final String sign = DigestUtils.md5Hex(data);
        log.info("====> genMd5Sign: {}", sign);
        return sign;
    }
}


